package com.blog.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.blog.domain.ResponseResult;
import com.blog.enums.AppHttpCodeEnum;
import com.blog.exception.SystemException;
import com.blog.service.UploadService;
import com.blog.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {

	@Autowired
	private AliOssUtil aliOssUtil;
	@Override
	public ResponseResult uploadImg(MultipartFile img) {
		//如果判断通过上传到oss
		try {
			//原始文件名
			String originalFilename = img.getOriginalFilename();
			if (!(originalFilename.endsWith(".png") || originalFilename.endsWith(".jpg"))){
				throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
			}
			//截取原始文件名的后缀,扩展名
			String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
			String datePath = sdf.format(new Date());
			String filename = datePath+UUID.randomUUID().toString() + substring;

			String url = aliOssUtil.upload(img.getBytes(), filename);
			return ResponseResult.okResult(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_FAILURE);
	}
}
